<script lang="ts" setup>
import { ref, reactive, defineEmits } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormRules, FormInstance } from 'element-plus'
import { ButtonGetSmsCode } from '@/components/ButtonGetSmsCode'
import * as PwdApi from '@/api/password'
const message = useMessage() // 消息弹窗

defineOptions({ name: 'PwdForget' })

const { t } = useI18n()
const ruleFormRef2 = ref<FormInstance>()
// 手机号找回
const sms_scene: number = 4
interface RuleForm2 {
  mobile: string
  code: string
  password: string
  password2: string
}
const formData2 = reactive({
  mobile: '',
  code: '',
  password: '',
  password2: ''
})

const validatePass = (rule: any, value: any, callback: any) => {
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{8,16}$/
  if (value === '') {
    callback(new Error(t('forget.phPwd2')))
  } else if (!passwordRegex.test(value)) {
    callback(new Error(t('forget.errPwdTip')))
  } else {
    callback()
  }
}

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error(t('forget.phPwd2')))
  } else if (value !== formData2.password) {
    callback(new Error(t('forget.errPwdTip2')))
  } else {
    callback()
  }
}

const validateMobile = (rule, value, callback) => {
  if (!value) {
    return new Error(t('forget.phMobile') + t('forget.labelMobile'))
  } else {
    const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
    const isPhone = reg.test(value)
    value = Number(value) //转换为数字
    if (typeof value === 'number' && !isNaN(value)) {
      //判断是否为数字
      value = value.toString() //转换成字符串
      if (value.length < 0 || value.length > 12 || !isPhone) {
        //判断是否为11位手机号
        callback(new Error(t('page_sys.user.tipSjh')))
      } else {
        callback()
      }
    } else {
      callback(new Error(t('forget.phMobile') + t('forget.labelMobile')))
    }
  }
}

const rules2 = reactive<FormRules<RuleForm2>>({
  mobile: [
    { required: true, message: t('forget.phMobile') + t('forget.labelMobile'), trigger: 'blur' },
    // { min: 1, max: 11, message: '', trigger: 'blur' }
    { validator: validateMobile, trigger: 'blur' }
  ],
  code: [
    { required: true, message: t('forget.phCode') + t('forget.labelCode'), trigger: 'blur' }
    // { min: 1, max: 10, message: '', trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('forget.phPwd'), trigger: 'blur' },
    // { min: 1, max: 50, message: '', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  password2: [
    { required: true, message: t('forget.phPwd2'), trigger: 'blur' },
    { min: 8, max: 16, message: t('forget.errPwdTip'), trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
})
// methods
const isSubmitting = ref(false)
const emit = defineEmits(['destroy', 'success'])
const handleDestory = () => {
  emit('destroy', {})
}
const handleSuccess = () => {
  emit('success', {})
}

const handleResetPwdByMobile = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const valid = await formEl.validate()
  if (valid) {
    isSubmitting.value = true
    try {
      const result = await PwdApi.resetPwdByMobile(formData2)
      if (result) {
        message.success(t('common.updateSuccess'))
        setTimeout(() => {
          handleDestory()
        }, 500)
      }
    } catch (e) {}
    isSubmitting.value = false
  }
}
</script>

<template>
  <div class="pwd-forget">
    <el-form
      ref="ruleFormRef2"
      :model="formData2"
      :rules="rules2"
      label-width="auto"
      label-position="right"
    >
      <el-form-item :label="t('forget.labelMobile')" prop="mobile">
        <el-input v-model="formData2.mobile" maxlength="11" :placeholder="t('forget.phMobile')" />
      </el-form-item>

      <el-form-item :label="t('forget.labelCode')" prop="code">
        <div class="input-sms-code">
          <el-input
            v-model="formData2.code"
            maxlength="10"
            :placeholder="t('forget.phCode')"
            style="margin-right: 20px"
          />
          <ButtonGetSmsCode
            :mobile="formData2.mobile"
            :scene="sms_scene"
            :serviceUrl="PwdApi.getResetPwdSmsCodeUrl"
          />
        </div>
      </el-form-item>

      <el-form-item :label="t('forget.labelPwd')" prop="password">
        <el-input
          v-model="formData2.password"
          maxlength="16"
          :placeholder="t('forget.phPwd')"
          type="password"
          show-password
          autocomplete="new-password"
        />
      </el-form-item>

      <el-form-item :label="t('forget.labelPwd2')" prop="password2">
        <el-input
          v-model="formData2.password2"
          maxlength="16"
          :placeholder="t('forget.phPwd2')"
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item>
        <div class="form-footer">
          <el-button round @click="handleDestory">{{ t('forget.txtCancel') }}</el-button>
          <el-button
            type="primary"
            round
            :loading="isSubmitting"
            @click="handleResetPwdByMobile(ruleFormRef2)"
            >{{ t('forget.txtSubmit') }}</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss">
.dark {
  .pwd-forget {
    svg {
      color: #fff;
    }
  }
}
.pwd-forget {
  .el-input__icon {
    width: 18px;
    height: 16px;

    svg {
      width: 100%;
      height: 100%;
    }
  }

  .el-form-item__error {
    margin-top: 14px;
    position: relative;
    font-size: 14px;
    top: 0;
  }
}
</style>
<style lang="scss" scoped>
.pwd-forget {
  margin: 0px -16px;
  padding: 16px 24px 0;
  border-top: solid 1px rgba(255, 255, 255, 0.1);

  .form-footer {
    display: flex;
    justify-content: end;
    width: 100%;

    .el-button {
      width: 80px;
    }
  }

  .input-sms-code {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }
}
</style>
